# coding: utf-8
import traceback
from flask_restful import Resource, reqparse

from . import conversation_api
from ..services.conversations import ConversationsService

"""
会话管理相关接口
"""

# 初始化Flask-RESTful的Api实例，使用现有的site_api蓝图


class ConversationsApi(Resource):
    """Resource for conversations management."""
    
    def get(self):
        """Get conversations list with pagination."""
        # 参数校验
        parser = reqparse.RequestParser()
        parser.add_argument("page", type=int, required=False, default=1, location="args", help="页码必须为整数")
        parser.add_argument("per_page", type=int, required=False, default=10, location="args", help="每页数量必须为整数")
        # 添加更多入参校验
        parser.add_argument("status", type=int, required=False, location="args", help="状态过滤必须为整数")
        parser.add_argument("user_id", type=str, required=False, location="args", help="用户ID过滤")
        parser.add_argument("is_delete", type=int, required=False, location="args", help="删除状态过滤必须为整数")
        
        # 验证参数
        args = parser.parse_args()
        
        # 校验参数有效性
        if args["page"] < 1:
            return {'result': 'fail', 'message': '页码必须大于等于1'}
        if args["per_page"] < 1 or args["per_page"] > 100:
            return {'result': 'fail', 'message': '每页数量必须在1-100之间'}
        
        try:
            # 准备过滤条件
            filters = {}
            if args["status"] is not None:
                filters["status"] = args["status"]
            if args["user_id"] is not None:
                filters["user_id"] = args["user_id"]
            if args["is_delete"] is not None:
                filters["is_delete"] = args["is_delete"]
            
            # 调用service层处理业务逻辑
            conversations_data = ConversationsService.get_conversations(
                page=args["page"],
                per_page=args["per_page"],
                filters=filters
            )
            
            # 处理null值
            processed_data = ConversationsService.process_null_values(conversations_data)
            
            # 构造返回结果
            result = {
                'result': 'success',
                'data': processed_data
            }
            
            return result
        except Exception as e:
            print('【获取会话列表错误:】', traceback.format_exc())
            return {'result': 'fail', 'message': 'Server error occurred: {}'.format(str(e))}

class ConversationRecordsApi(Resource):
    """Resource for getting conversation records with pagination."""
    
    def get(self, conversation_id):
        """Get records by conversation ID with pagination."""
        # 参数校验
        parser = reqparse.RequestParser()
        parser.add_argument("page", type=int, required=False, default=1, location="args", help="页码必须为整数")
        parser.add_argument("per_page", type=int, required=False, default=50, location="args", help="每页数量必须为整数")
        
        # 验证参数
        args = parser.parse_args()
        
        # 校验参数有效性
        if args["page"] < 1:
            return {'result': 'fail', 'message': '页码必须大于等于1'}
        if args["per_page"] < 1 or args["per_page"] > 200:
            return {'result': 'fail', 'message': '每页数量必须在1-200之间'}
        
        try:
            # 调用service层处理业务逻辑
            records_data = ConversationsService.get_conversation_records(
                conversation_id=conversation_id,
                page=args["page"],
                per_page=args["per_page"]
            )
            
            # 构造返回结果
            result = {
                'result': 'success',
                'data': records_data
            }
            
            return result
        except Exception as e:
            print('【获取会话记录错误:】', traceback.format_exc())
            return {'result': 'fail', 'message': 'Server error occurred: {}'.format(str(e))}

class CreateRecordApi(Resource):
    """Resource for creating a new conversation record."""
    
    def post(self):
        """Create a new record with step title and console output."""
        # 参数校验
        parser = reqparse.RequestParser()
        parser.add_argument("conversation_id", type=str, required=True, location="json", help="会话ID不能为空")
        parser.add_argument("user_id", type=str, required=True, location="json", help="用户ID不能为空")
        parser.add_argument("data_conf_id", type=str, required=True, location="json", help="数据配置ID不能为空")
        parser.add_argument("step_title", type=str, required=True, location="json", help="步骤标题不能为空")
        parser.add_argument("current_state", type=str, required=True, location="json", help="控制台输出内容不能为空")
        parser.add_argument("status", type=int, required=False, default=10, location="json", help="状态必须为整数")
        parser.add_argument("is_delete", type=int, required=False, default=0, location="json", help="删除状态必须为整数")
        parser.add_argument("message_type", type=str, required=False, default="bot", location="json", help="消息类型")
        
        # 验证参数
        args = parser.parse_args()
        
        try:
            # 准备数据
            record_data = {
                'conversation_id': args["conversation_id"],
                'user_id': args["user_id"],
                'data_conf_id': args["data_conf_id"],
                'step_title': args["step_title"],
                'current_state': args["current_state"],
                'status': args["status"],
                'is_delete': args["is_delete"],
                'message_type': args["message_type"]
            }
            
            # 调用service层处理业务逻辑
            created_record = ConversationsService.create_record(record_data)
            
            # 构造返回结果
            result = {
                'result': 'success',
                'data': created_record
            }
            
            return result
        except Exception as e:
            print('【创建会话记录错误:】', traceback.format_exc())
            return {'result': 'fail', 'message': 'Server error occurred: {}'.format(str(e))}

# 注册路由
conversation_api.add_resource(ConversationsApi, "/list")
conversation_api.add_resource(ConversationRecordsApi, "/<string:conversation_id>/records")
conversation_api.add_resource(CreateRecordApi, "/records/create")